package com.qiantu.phone.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.event.RefreshSceneEvent;
import com.qiantu.phone.manager.SceneOperateManager;
import com.qiantu.phone.ui.activity.PanelBingingActivity;
import com.qiantu.phone.ui.activity.RoomDeviceActivity;
import com.qiantu.phone.ui.activity.SceneAddGuideActivity;
import com.qiantu.phone.ui.adapter.RoomManagerSceneAdapter;
import com.qiantu.phone.utils.SceneDetailUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class RoomSceneFragment extends AppFragment<AppActivity> {
    private RecyclerView sceneList;
    private LinearLayout ll_Noequipment;
    private TextView btn;
    private RoomManagerSceneAdapter sceneAdapter;

    private PanelBingingActivity mActivity;
    private int type;
    private String roomSerialNo;
    private SceneOperateManager mSceneOperateManager;
    private Handler mHandler;
    private ViewGroup sceneItemLongClickContainer;

    public RoomSceneFragment() {
    }

    public static RoomSceneFragment newInstance(int type,String roomSerialNo) {
        RoomSceneFragment fragment = new RoomSceneFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        fragment.type = type;
        fragment.roomSerialNo = roomSerialNo;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {}
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_room_scene_list;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        sceneList = findViewById(R.id.scene_list);
        ll_Noequipment = findViewById(R.id.ll_Noequipment);
        btn = findViewById(R.id.btn);
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
            btn.setVisibility(View.GONE);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        sceneList.setLayoutManager(gridLayoutManager);
        sceneAdapter = new RoomManagerSceneAdapter(getContext())
                .setSelectAct(false)
                .setShowFloorRoom(true)
                .setSingleSelect(true);
        sceneAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                SceneBean scene = sceneAdapter.getData().get(position);
                if(scene.getSceneSerialNo() == null){
                    gotoAddView(type,roomSerialNo);
                }else{
                    if(mSceneOperateManager == null){
                        mSceneOperateManager = new SceneOperateManager(getContext());
                        mSceneOperateManager.setInterrupListener(new SceneOperateManager.InterruptListener() {
                            @Override
                            public void updateInterrupt(int time) {
                                sceneInterrupt(position,time);
                            }
                        });
                    }
                    mSceneOperateManager.onClick(itemView, scene.getSceneSerialNo());
                }
            }
        });
        sceneAdapter.setOnItemLongClickListener(new BaseAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(RecyclerView recyclerView, View itemView, int position) {
                scrollTo(position);
                if (mHandler == null) {
                    mHandler = new Handler();
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int[] outLocation = new int[2];
                        itemView.getLocationOnScreen(outLocation);
                        SceneBean scene =  sceneAdapter.getData().get(position);
                        if(scene.getSceneSerialNo() != null){
                            ((RoomDeviceActivity) getActivity()).longClickSceneItem(outLocation[0], outLocation[1], itemView.getWidth(), itemView.getHeight(), scene, sceneAdapter.getData(),false);
                        }
                    }
                }, 50);

                return true;
            }
        });
        sceneAdapter.setOnChildClickListener(R.id.btn_interrupt_cancel, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                cancelInterrupt(position);
            }
        });
        sceneAdapter.setOnChildClickListener(R.id.setting, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                SceneDetailUtil.getSceneDetailAndToEdit(RoomSceneFragment.this, getAttachActivity(), sceneAdapter.getData().get(position).getSceneSerialNo());
            }
        });
        sceneList.setAdapter(sceneAdapter);
    }
    @Override
    protected void initData() {
        List<SceneBean> scenes;
        if(type == 0){
            scenes = LLSceneDBManager.getInstance(getContext()).getSceneByRoom(roomSerialNo);
        }else if(type == 1){
            scenes = LLSceneDBManager.getInstance(getContext()).getSceneByFloor(roomSerialNo);
        }else{
            scenes = LLSceneDBManager.getInstance(getContext()).getHouseAll();
        }
        if(scenes == null || scenes.size() == 0){
            No_equipment();
        }else{
            Ye_sequipment();
            if(AppApplication.getInstance().getCurHouseInfo().getRoleType() != 2){
                SceneBean emptyScene = new SceneBean();
                scenes.add(emptyScene);
            }
            sceneAdapter.setTotalData(scenes);
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        //没获取到数据才再刷新
        if(sceneAdapter.getAllSceneData() == null || sceneAdapter.getAllSceneData().size() == 0){
            initData();
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshSceneEvent(RefreshSceneEvent event) {
        initData();
    }

    private void No_equipment() {
        sceneList.setVisibility(View.GONE);
        ll_Noequipment.setVisibility(View.VISIBLE);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoAddView(type,roomSerialNo);
            }
        });
    }

    //当前变化有设备
    private void Ye_sequipment() {
        sceneList.setVisibility(View.VISIBLE);
        ll_Noequipment.setVisibility(View.GONE);
    }

    private void gotoAddView(int type,String roomSerialNo){
        Intent intent = new Intent(getContext(), SceneAddGuideActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("roomSerialNo", roomSerialNo);
        startActivity(intent);
    }

    public void scrollTo(int position) {
        if (sceneList != null) {
            sceneList.scrollToPosition(position);
//            ((HomeFragment)getParentFragment()).setAppBarLayoutOffset();
        }
    }

    public void sceneInterrupt(int position,int time){
        SceneBean sceneBean = sceneAdapter.getData().get(position);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis() + time*1000);
        sceneBean.setActionSettingExpireTime(format.format(date));
        LLSceneDBManager.getInstance(getContext()).updateExpireTime(sceneBean.getSceneSerialNo(),format.format(date));
        sceneAdapter.notifyDataSetChanged();
    }

    public void cancelInterrupt(int position){
        SceneBean sceneBean = sceneAdapter.getData().get(position);
        LLHttpManager.cancelInterrupMode(this, sceneBean.getSceneSerialNo(), new HttpCallback<HttpData<Void>>(this){
            public void onSucceed(HttpData<Void> result) {
                sceneBean.setActionSettingExpireTime("");
                LLSceneDBManager.getInstance(getContext()).updateExpireTime(sceneBean.getSceneSerialNo(),"");
                sceneAdapter.cancelTimer();
                sceneAdapter.notifyDataSetChanged();
            }
        });
    }
}
